﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExcelRef = Microsoft.Office.Interop.Excel;

namespace FX.CC.Andon.Utility.Common
{
    public class ExcelComHelper
    {
        public static bool ExcelToPDF(string srcFilePath, string targetFilePath)
        {
            ExcelRef.Application excelApplication = new ExcelRef.Application();
            excelApplication.ShowWindowsInTaskbar = false;
            ExcelRef.Workbook excelWorkBook = null;

            object paramMissing = Type.Missing;

            ExcelRef.XlFixedFormatType paramExportFormat = ExcelRef.XlFixedFormatType.xlTypePDF;
            ExcelRef.XlFixedFormatQuality paramExportQuality =
                ExcelRef.XlFixedFormatQuality.xlQualityMinimum;
            bool paramOpenAfterPublish = false;
            bool paramIncludeDocProps = false;
            bool paramIgnorePrintAreas = false;
            object paramFromPage = Type.Missing;
            object paramToPage = Type.Missing;

            try
            {
                // Open the source workbook.
                excelWorkBook = excelApplication.Workbooks.Open(srcFilePath,
                    paramMissing, paramMissing, paramMissing, paramMissing,
                    paramMissing, paramMissing, paramMissing, paramMissing,
                    paramMissing, paramMissing, paramMissing, paramMissing,
                    paramMissing, paramMissing);

                // Save it in the target format.
                if (excelWorkBook != null)
                    excelWorkBook.ExportAsFixedFormat(paramExportFormat,
                        targetFilePath, paramExportQuality,
                        paramIncludeDocProps, paramIgnorePrintAreas, paramFromPage,
                        paramToPage, paramOpenAfterPublish,
                        paramMissing);

                return true;
            }
            catch (Exception ex)
            {
                // Respond to the error.
                return false;
            }
            finally
            {
                // Close the workbook object.
                if (excelWorkBook != null)
                {
                    excelWorkBook.Close(false, paramMissing, paramMissing);
                    excelWorkBook = null;
                }

                // Quit Excel and release the ApplicationClass object.
                if (excelApplication != null)
                {
                    excelApplication.Quit();
                    excelApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
    }
}
